<template>
    <!-- Single root element -->
    <view class="container">
        <div class="form">
            <!-- 游戏区服 -->
            <div class="form-item">
                <text class="label">游戏区服</text>
                <div class="handle" @click="showServerPicker">
                    <view class="selected-tag">
                         {{ selectedServerText || '请选择您所在的区服' }}
                        <image src="../../static/icons/arrow-down.png"></image>
                    </view>
                </div>
            </div>

            <!-- 代练类型 -->
            <div class="form-item">
                <text class="label">代练类型</text>
                <div class="handle" @click="showModePicker">
                    <view class="selected-tag">
                        {{ selectedMode || '请选择代练类型' }}
                        <image src="../../static/icons/arrow-down.png"></image>
                    </view>
                </div>
            </div>

            <!-- 游戏模式 -->
            <div class="form-item" v-if="selectedMode === '代币' || selectedMode === '宝典'">
                <text class="label">游戏模式</text>
                <div class="handle" @click="showGameModePicker">
                    <view class="selected-tag">
                        {{ gameMode || '请选择游戏模式' }}
                        <image src="../../static/icons/arrow-down.png"></image>
                    </view>
                </div>
            </div>

            <!-- 通行证 -->
            <div class="form-item pass-item" v-if="selectedMode === '代币' || selectedMode === '宝典'">
                <text class="label">通行证</text>
                <div class="handle pass-handle">
                    <uni-data-checkbox mode="button" v-model="selectPass" :localdata="passOptions"></uni-data-checkbox>
                </div>
            </div>
            <!-- 代练任务（代币） -->
            <div class="form-item" v-if="selectedMode === '代币'">
                <text class="label">代练任务</text>
                <div class="handle" @click="showCurrentTokensPicker">
                    <view class="selected-tag">
                        {{ tokensDisplay || '请输入当前代币和目标代币' }}
                        <image src="../../static/icons/arrow-down.png"></image>
                    </view>
                </div>
            </div>
            <!-- 代练任务（宝典） -->
            <div class="form-item" v-if="selectedMode === '宝典'">
                <text class="label">代练任务</text>
                <div class="handle" @click="showCurrentLevelPicker">
                    <view class="selected-tag">
                        {{ levelsDisplay || '请输入当前等级和目标等级'}}
                        <image src="../../static/icons/arrow-down.png"></image>
                    </view>
                </div>
            </div>

            <!-- 排位类型 -->
            <div class="form-item" v-if="selectedMode === '排位赛' || selectedMode === '定位赛'">
                <text class="label">排位类型</text>
                <div class="handle" @click="showRankTypePicker">
                    <view class="selected-tag">
                        {{ rankType || '请选择组排方式' }}
                        <image src="../../static/icons/arrow-down.png"></image>
                    </view>
                </div>
            </div>
            <!-- 代练任务（排位赛） -->
            <div class="form-item" v-if="selectedMode === '排位赛'">
                <text class="label">代练任务</text>
                <div class="handle" @click="showCurrentTaskTypePicker">
                    <view class="selected-tag">
                        {{ rankDisplay || '请选择当前段位和目标段位' }}
                        <image src="../../static/icons/arrow-down.png"></image>
                    </view>
                </div>
            </div>
            <!-- 当前胜点 -->
            <div class="form-item" v-if="selectedMode === '排位赛'">
                <text class="label">当前胜点</text>
                <div class="handle" @click="showCurrentScorePicker">
                    <view class="selected-tag">
                        {{ currentScore !== '' ? currentScore : '请输入当前胜点' }}
                        <image src="../../static/icons/arrow-down.png"></image>
                    </view>
                </div>
            </div>
            <!-- 上赛季段位 -->
            <div class="form-item" v-if="selectedMode === '定位赛'">
                <text class="label">上赛季段位</text>
                <div class="handle" @click="showBeforeLevelPicker">
                    <view class="selected-tag">
                        {{ beforeLevel || '请选择上赛季段位' }}
                        <image src="../../static/icons/arrow-down.png"></image>
                    </view>
                </div>
            </div>
            <!-- 需打场次 -->
            <div class="form-item" v-if="selectedMode === '定位赛'">
                <text class="label">需打场次</text>
                <div class="handle" @click="showNeedGamesPicker">
                    <view class="selected-tag">
                        {{ needGames || '请选择需打场次' }}
                        <image src="../../static/icons/arrow-down.png"></image>
                    </view>
                </div>
            </div>
        </div>

        <!-- Popups -->
        <!-- 游戏区服选择弹窗 -->
        <uni-popup ref="serverPopup" type="bottom">
            <view class="popup-content">
                <div class="top">请选择游戏区服</div>
                <div class="body">
                    <scroll-view scroll-y class="popup-nav">
                        <view v-for="(group, groupIndex) in serverTree" :key="groupIndex" class="nav-item"
                            :class="{ active: selectedGroupIndex === groupIndex }" @click="selectGroup(groupIndex)">
                            {{ group.text }}
                        </view>
                    </scroll-view>
                    <scroll-view scroll-y class="popup-scroll">
                        <view v-if="selectedGroupIndex !== null && serverTree[selectedGroupIndex]" class="popup-group">
                            <view v-for="(item, itemIndex) in serverTree[selectedGroupIndex].children" :key="itemIndex"
                                class="popup-item" @click="selectServerItem(item)">
                                {{ item.text }}
                            </view>
                        </view>
                        <view v-else class="popup-empty">请选择左侧分类</view>
                    </scroll-view>
                </div>
                 <view class="popup-footer" @click="hideServerPicker">取消</view>
            </view>
        </uni-popup>

        <!-- 代练类型选择弹窗 -->
        <uni-popup ref="modePopup" type="bottom">
            <view class="popup-content">
                 <div class="top">请选择代练类型</div>
                <scroll-view scroll-y class="popup-scroll">
                    <view v-for="(item, index) in modeTree" :key="index" class="popup-item" @click="selectModeItem(item)">
                        {{ item.text }}
                    </view>
                </scroll-view>
                <view class="popup-footer" @click="hideModePicker">取消</view>
            </view>
        </uni-popup>

        <!-- 游戏模式选择弹窗 -->
        <uni-popup ref="gameModePopup" type="bottom">
            <view class="popup-content">
                 <div class="top">请选择游戏模式</div>
                <scroll-view scroll-y class="popup-scroll">
                    <view v-for="(item, index) in gameModeTree" :key="index" class="popup-item"
                        @click="selectGameModeItem(item)">
                        {{ item.text }}
                    </view>
                </scroll-view>
                <view class="popup-footer" @click="hideGameModePicker">取消</view>
            </view>
        </uni-popup>

        <!-- 代练任务（代币）弹窗 -->
        <uni-popup ref="currentTokensPopup" type="bottom">
            <view class="popup-content input-popup">
                <div class="top">代币数量</div>
                <div class="input-row">
                    <span>当前代币</span>
                    <input type="number" placeholder="请输入当前代币" v-model="tempCurrentTokens">
                </div>
                <div class="input-row">
                    <span>目标代币</span>
                    <input type="number" placeholder="请输入目标代币" v-model="tempToTokens">
                </div>
                <view class="popup-footer2">
                    <span class="cancel" @click="hideCurrentTokensPicker">取消</span>
                    <span class="confirm" @click="confirmCurrentTokensPicker">确认</span>
                </view>
            </view>
        </uni-popup>

        <!-- 代练任务（宝典）弹窗 -->
        <uni-popup ref="currentLevelPopup" type="bottom">
             <view class="popup-content input-popup">
                 <div class="top">宝典等级</div>
                <div class="input-row">
                    <span>当前等级</span>
                    <input type="number" placeholder="请输入当前等级" v-model="tempCurrentLevel">
                </div>
                <div class="input-row">
                    <span>目标等级</span>
                    <input type="number" placeholder="请输入目标等级" v-model="tempToLevel">
                </div>
                <view class="popup-footer2">
                    <span class="cancel" @click="hideCurrentLevelPicker">取消</span>
                    <span class="confirm" @click="confirmCurrentLevelPicker">确认</span>
                </view>
            </view>
        </uni-popup>

        <!-- 排位类型选择弹窗 -->
        <uni-popup ref="rankTypePopup" type="bottom">
            <view class="popup-content">
                 <div class="top">请选择排位类型</div>
                <scroll-view scroll-y class="popup-scroll">
                    <view v-for="(item, index) in rankTypeTree" :key="index" class="popup-item"
                        @click="selectRankTypeItem(item)">
                        {{ item.text }}
                    </view>
                </scroll-view>
                <view class="popup-footer" @click="hideRankTypePicker">取消</view>
            </view>
        </uni-popup>

        <!-- 当前段位选择弹窗 -->
        <uni-popup ref="currentTaskTypePopup" type="bottom">
            <view class="popup-content">
                <div class="top">请选择当前段位</div>
                <div class="body">
                    <scroll-view scroll-y class="popup-nav">
                        <view v-for="(group, groupIndex) in Task" :key="groupIndex" class="nav-item"
                            :class="{ active: selectedCurrentTaskGroupIndex === groupIndex }"
                            @click="selectCurrentTaskGroup(groupIndex)">
                            {{ group.text }}
                        </view>
                    </scroll-view>
                    <scroll-view scroll-y class="popup-scroll">
                        <view v-if="selectedCurrentTaskGroupIndex !== null && Task[selectedCurrentTaskGroupIndex]" class="popup-group">
                             <div class="popup-item-body rank-body">
                                 <view v-for="(item, itemIndex) in Task[selectedCurrentTaskGroupIndex].children" :key="itemIndex"
                                    @click="selectCurrentTaskItem(Task[selectedCurrentTaskGroupIndex].text, item.text)" class="popup-item-body-item rank-item">
                                     <span>{{ Task[selectedCurrentTaskGroupIndex].text }} {{ item.text }}</span>
                                </view>
                             </div>
                        </view>
                        <view v-else class="popup-empty">请选择左侧分类</view>
                    </scroll-view>
                </div>
                 <view class="popup-footer" @click="hideCurrentTaskTypePicker">取消</view>
            </view>
        </uni-popup>

        <!-- 目标段位选择弹窗 -->
        <uni-popup ref="toTaskTypePopup" type="bottom">
            <view class="popup-content">
                <div class="top">请选择目标段位</div>
                 <div class="body">
                    <scroll-view scroll-y class="popup-nav">
                        <view v-for="(group, groupIndex) in Task" :key="groupIndex" class="nav-item"
                            :class="{ active: selectedToTaskGroupIndex === groupIndex }"
                            @click="selectToTaskGroup(groupIndex)">
                            {{ group.text }}
                        </view>
                    </scroll-view>
                    <scroll-view scroll-y class="popup-scroll">
                        <view v-if="selectedToTaskGroupIndex !== null && Task[selectedToTaskGroupIndex]" class="popup-group">
                             <div class="popup-item-body rank-body">
                                 <view v-for="(item, itemIndex) in Task[selectedToTaskGroupIndex].children" :key="itemIndex"
                                    @click="selectToTaskItem(Task[selectedToTaskGroupIndex].text, item.text)" class="popup-item-body-item rank-item">
                                     <span>{{ Task[selectedToTaskGroupIndex].text }} {{ item.text }}</span>
                                </view>
                             </div>
                        </view>
                        <view v-else class="popup-empty">请选择左侧分类</view>
                    </scroll-view>
                </div>
                 <view class="popup-footer" @click="hideToTaskTypePicker">取消</view>
            </view>
        </uni-popup>

        <!-- 当前胜点弹窗 -->
        <uni-popup ref="currentScorePopup" type="bottom">
             <view class="popup-content input-popup">
                 <div class="top">当前胜点</div>
                 <div class="input-row score-input">
                    <span>胜点</span>
                    <input type="number" placeholder="请输入当前胜点 0-99" v-model="tempCurrentScore">
                 </div>
                <view class="popup-footer2">
                    <span class="cancel" @click="hideCurrentScorePicker">取消</span>
                    <span class="confirm" @click="confirmCurrentScorePicker">确认</span>
                </view>
            </view>
        </uni-popup>

        <!-- 上赛季段位选择弹窗 -->
        <uni-popup ref="beforeLevelPopup" type="bottom">
            <view class="popup-content">
                 <div class="top">请选择上赛季段位</div>
                <scroll-view scroll-y class="popup-scroll">
                    <view v-for="(item, index) in beforeLevelTree" :key="index" class="popup-item"
                        @click="selectBeforeLevelItem(item)">
                        {{ item.text }}
                    </view>
                </scroll-view>
                <view class="popup-footer" @click="hideBeforeLevelPicker">取消</view>
            </view>
        </uni-popup>

        <!-- 需打场次选择器弹窗 -->
        <uni-popup ref="needGamesPopup" type="bottom">
            <view class="popup-content">
                 <div class="top">请选择需打场次</div>
                <scroll-view scroll-y class="popup-scroll">
                    <view v-for="(item, index) in needGamesTree" :key="index" class="popup-item"
                        @click="selectNeedGamesItem(item)">
                        {{ item.text }}
                    </view>
                </scroll-view>
                <view class="popup-footer" @click="hideNeedGamesPicker">取消</view>
            </view>
        </uni-popup>

        <!-- 订单信息区域 -->
        <div class="orderMsg">
            <div class="pay">
                <image src="../../static/icons/pay.png"></image>
                 <div class="text">建议出价 <span class="price-highlight">{{ suggestedPrice }}元</span></div>
            </div>
            <div class="time">
                <image src="../../static/icons/time.png"></image>
                <div class="text">预计时限 <span class="time-highlight">{{ estimatedTime }}小时</span></div>
            </div>
        </div>

        <!-- Placeholder for footer -->
        <view class="footer-placeholder"></view>

        <!-- 底部按钮 -->
        <div class="footer">
            <div class="tip">代练通全程为您服务</div>
            <div class="button" @click="submitOrder">下一步</div>
        </div>
    </view>
</template>

<script>
// Removed Composition API imports

export default {
  components: {},
  data() {
    return {
      // Server Selection
      serverTree: [
         {
            text: '电信',
            value: "电信",
            children: [
                { text: '艾欧尼亚', value: "艾欧尼亚" },
                { text: '祖安', value: "祖安" },
                { text: '诺克萨斯', value: "诺克萨斯" },
                { text: '班德尔城', value: "班德尔城" },
                { text: '皮尔特沃夫', value: "皮尔特沃夫" },
                { text: '战争学院', value: "战争学院" },
                { text: '巨神峰', value: "巨神峰" },
                { text: '雷瑟守备', value: "雷瑟守备" },
                { text: '裁决之地', value: "裁决之地" },
                { text: '黑色玫瑰', value: "黑色玫瑰" },
                { text: '暗影岛', value: "暗影岛" },
                { text: '钢铁烈阳', value: "钢铁烈阳" },
                { text: '均衡教派', value: "均衡教派" },
                { text: '水晶之痕', value: "水晶之痕" },
                { text: '影流', value: "影流" },
                { text: '守望之海', value: "守望之海" },
                { text: '征服之海', value: "征服之海" },
                { text: '卡拉曼达', value: "卡拉曼达" },
                { text: '皮城警备', value: "皮城警备" },
            ]
        },
        {
            text: '网通',
            value: "网通",
            children: [
                { text: '比尔吉沃特', value: "比尔吉沃特" },
                { text: '德玛西亚', value: "德玛西亚" },
                { text: '弗雷尔卓德', value: "弗雷尔卓德" },
                { text: '无畏先锋', value: "无畏先锋" },
                { text: '恕瑞玛', value: "恕瑞玛" },
                { text: '扭曲丛林', value: "扭曲丛林" },
                { text: '巨龙之巢', value: "巨龙之巢" }
            ]
        },
        {
            text: '全网络',
            value: "全网络",
            children: [
                { text: '男爵领域', value: "男爵领域" },
                { text: '峡谷之巅', value: "峡谷之巅" }
            ]
        },
        {
            text: '其它',
            value: "其它",
            children: [
                { text: '教育网专区', value: "教育网专区" }
            ]
        },
      ],
      selectedServer: "艾欧尼亚",
      selectedGroupIndex: 0,

      // Mode Selection
      modeTree: [
        { text: '排位赛', value: "排位赛" }, { text: '定位赛', value: "定位赛" },
        { text: '代币', value: "代币" }, { text: '宝典', value: "宝典" },
      ],
      selectedMode: "排位赛",

      // Game Mode Selection (for 代币/宝典)
      gameModeTree: [
        { text: '不限模式', value: "不限模式" }, { text: '禁止排位', value: "禁止排位" },
        { text: '仅限匹配', value: "仅限匹配" }, { text: '仅限云顶', value: "仅限云顶" },
      ],
      gameMode: "不限模式",

      // Pass Selection (for 代币/宝典)
      passOptions: [
        { text: '已有通行证', value: '已有通行证' },
        { text: '已有点卷', value: '已有点卷' }
      ],
      selectPass: "已有通行证", // Default selection

      // Token Task (for 代币)
      currentTokens: '',
      toTokens: '',
      tempCurrentTokens: '', // Temporary values for popup input
      tempToTokens: '',

      // Level Task (for 宝典)
      currentLevel: '',
      toLevel: '',
      tempCurrentLevel: '', // Temporary values for popup input
      tempToLevel: '',

      // Rank Type Selection (for 排位赛/定位赛)
      rankTypeTree: [
        { text: '单双排', value: "单双排" },
        { text: '灵活组排', value: "灵活组排" }
      ],
      rankType: "",

      // Rank Task (for 排位赛)
      Task: [], // Populated in mounted()
      selectedCurrentTask: "",
      selectedCurrentTaskGroupIndex: 0,
      selectedToTask: "",
      selectedToTaskGroupIndex: 0,

      // Current Score (for 排位赛)
      currentScore: '',
      tempCurrentScore: '', // Temporary value for popup input

      // Before Level (for 定位赛)
      beforeLevelTree: [
        { text: '新号', value: "新号" }, { text: '黑铁', value: "黑铁" }, { text: '青铜', value: "青铜" },
        { text: '白银', value: "白银" }, { text: '黄金', value: "黄金" }, { text: '铂金', value: "铂金" },
        { text: '翡翠', value: "翡翠" }, { text: '钻石', value: "钻石" }, { text: '大师', value: "大师" },
      ],
      beforeLevel: "",

      // Need Games (for 定位赛)
      needGamesTree: [
        { text: '1场', value: "1场" }, { text: '2场', value: "2场" }, { text: '3场', value: "3场" },
        { text: '4场', value: "4场" }, { text: '5场', value: "5场" }
      ],
      needGames: "",

      // Price/Time display
      suggestedPrice: 87, // Example static value
      estimatedTime: 47, // Example static value
    };
  },
  computed: {
      selectedServerText() {
          if (this.serverTree && this.serverTree[this.selectedGroupIndex]) {
              return `${this.serverTree[this.selectedGroupIndex].text}/${this.selectedServer}`;
          }
          return '请选择您所在的区服';
      },
      tokensDisplay() {
          if (this.currentTokens !== '' && this.toTokens !== '') {
              return `代币 ${this.currentTokens} 个 - ${this.toTokens} 个`;
          }
          return ''
      },
       levelsDisplay() {
          if (this.currentLevel !== '' && this.toLevel !== '') {
              return `${this.currentLevel} 级 - ${this.toLevel} 级`;
          }
          return ''
      },
      rankDisplay() {
           if (this.selectedCurrentTask && this.selectedToTask) {
               return `${this.selectedCurrentTask} - ${this.selectedToTask}`;
           }
           return ''
      }
      // Add computed properties for price/time if they depend on selections
  },
  mounted() {
    this.createTaskList();
  },
  methods: {
    // --- Popup Show/Hide Methods --- 
    showPopup(refName) {
        if (this.$refs[refName]) {
            this.$refs[refName].open();
        } else {
             console.error(`${refName} ref not ready`);
        }
    },
    hidePopup(refName) {
         if (this.$refs[refName]) {
            this.$refs[refName].close();
        } else {
             console.error(`${refName} ref not ready`);
        }
    },

    // --- Specific Picker Methods --- 
    showServerPicker() { this.showPopup('serverPopup'); },
    hideServerPicker() { this.hidePopup('serverPopup'); },
    selectGroup(index) { this.selectedGroupIndex = index; },
    selectServerItem(item) {
        this.selectedServer = item.text;
        this.hideServerPicker();
    },

    showModePicker() { this.showPopup('modePopup'); },
    hideModePicker() { this.hidePopup('modePopup'); },
    selectModeItem(item) {
        this.selectedMode = item.text;
        // Reset conditional fields
        this.resetConditionalFields();
        this.hideModePicker();
    },

    showGameModePicker() { this.showPopup('gameModePopup'); },
    hideGameModePicker() { this.hidePopup('gameModePopup'); },
    selectGameModeItem(item) {
        this.gameMode = item.text;
        this.hideGameModePicker();
    },

    showCurrentTokensPicker() {
        // Load current values into temporary holders for the popup input
        this.tempCurrentTokens = this.currentTokens;
        this.tempToTokens = this.toTokens;
        this.showPopup('currentTokensPopup');
    },
    hideCurrentTokensPicker() { this.hidePopup('currentTokensPopup'); },
    confirmCurrentTokensPicker() {
        // Validate temp values if needed
        this.currentTokens = this.tempCurrentTokens;
        this.toTokens = this.tempToTokens;
        this.hideCurrentTokensPicker();
    },

    showCurrentLevelPicker() {
         this.tempCurrentLevel = this.currentLevel;
         this.tempToLevel = this.toLevel;
         this.showPopup('currentLevelPopup');
    },
    hideCurrentLevelPicker() { this.hidePopup('currentLevelPopup'); },
    confirmCurrentLevelPicker() {
        this.currentLevel = this.tempCurrentLevel;
        this.toLevel = this.tempToLevel;
        this.hideCurrentLevelPicker();
    },

    showRankTypePicker() { this.showPopup('rankTypePopup'); },
    hideRankTypePicker() { this.hidePopup('rankTypePopup'); },
    selectRankTypeItem(item) {
        this.rankType = item.text;
        this.hideRankTypePicker();
    },

    // Task/Rank Methods
    createTaskList() {
        const tiers = ['黑铁', '青铜', '白银', '黄金', '铂金', '翡翠', '钻石', '大师', '宗师', '王者']; // Added Grandmaster/Challenger
        const taskList = [];
        tiers.forEach(tier => {
            let tierItem = { text: tier, value: tier, children: [] };
            // Ranks within tiers (e.g., IV, III, II, I or Points for high ranks)
             let children;
            if (['大师', '宗师', '王者'].includes(tier)) {
                 children = [{ text: '(胜点)', value: '胜点' }]; // Only points for high ranks
            } else {
                 // Assuming IV-I for other ranks
                 children = [{ text: 'IV', value: 'IV' }, { text: 'III', value: 'III' }, { text: 'II', value: 'II' }, { text: 'I', value: 'I' }];
            }
            tierItem.children = children;
            taskList.push(tierItem);
        });
        this.Task = taskList;
    },
    showCurrentTaskTypePicker() { this.showPopup('currentTaskTypePopup'); },
    hideCurrentTaskTypePicker() { this.hidePopup('currentTaskTypePopup'); },
    selectCurrentTaskGroup(index) { this.selectedCurrentTaskGroupIndex = index; },
    selectCurrentTaskItem(tier, subTier) {
        this.selectedCurrentTask = `${tier} ${subTier}`.replace(' (胜点)',''); // Display clean rank
        this.hideCurrentTaskTypePicker();
        // Automatically open target rank picker if current is selected
        if (this.selectedMode === '排位赛') {
            this.showToTaskTypePicker();
        }
    },

    showToTaskTypePicker() { this.showPopup('toTaskTypePopup'); },
    hideToTaskTypePicker() { this.hidePopup('toTaskTypePopup'); },
    selectToTaskGroup(index) { this.selectedToTaskGroupIndex = index; },
    selectToTaskItem(tier, subTier) {
         this.selectedToTask = `${tier} ${subTier}`.replace(' (胜点)','');
        this.hideToTaskTypePicker();
        // Add validation: target must be >= current
        this.validateRankOrder();
    },

    validateRankOrder() {
        const findRankIndex = (rankString) => {
            if (!rankString) return -1;
            const parts = rankString.split(' ');
            const tier = parts[0];
            const subTier = parts[1] || '胜点'; // Default to points if no sub-tier

            const tierIndex = this.Task.findIndex(t => t.text === tier);
            if (tierIndex === -1) return -1;

            const subTierIndex = this.Task[tierIndex].children.findIndex(s => s.value === subTier);
            if (subTierIndex === -1 && subTier !== '胜点') return -1;
             // Assign a large number for tier index, and sub-tier index within that
             // Treat '胜点' as higher than I (index 3)
            const subIndexValue = (subTier === '胜点') ? 4 : subTierIndex;
            return tierIndex * 10 + subIndexValue; // Simple weighted index
        };

        const currentIndex = findRankIndex(this.selectedCurrentTask);
        const targetIndex = findRankIndex(this.selectedToTask);

        if (currentIndex !== -1 && targetIndex !== -1 && targetIndex < currentIndex) {
            uni.showToast({ title: '目标段位不能低于当前段位', icon: 'none' });
            this.selectedToTask = ''; // Reset target rank
            return false;
        }
         return true;
    },

    showCurrentScorePicker() {
        this.tempCurrentScore = this.currentScore;
        this.showPopup('currentScorePopup');
    },
    hideCurrentScorePicker() { this.hidePopup('currentScorePopup'); },
    confirmCurrentScorePicker() {
         // Validate 0-99
        const score = parseInt(this.tempCurrentScore);
        if (isNaN(score) || score < 0 || score > 99) {
            uni.showToast({ title: '请输入0-99的胜点', icon: 'none' });
            return;
        }
        this.currentScore = this.tempCurrentScore;
        this.hideCurrentScorePicker();
    },

    showBeforeLevelPicker() { this.showPopup('beforeLevelPopup'); },
    hideBeforeLevelPicker() { this.hidePopup('beforeLevelPopup'); },
    selectBeforeLevelItem(item) {
        this.beforeLevel = item.text;
        this.hideBeforeLevelPicker();
    },

    showNeedGamesPicker() { this.showPopup('needGamesPopup'); },
    hideNeedGamesPicker() { this.hidePopup('needGamesPopup'); },
    selectNeedGamesItem(item) {
        this.needGames = item.text;
        this.hideNeedGamesPicker();
    },

    // --- Helper Methods ---
    resetConditionalFields() {
        // Called when selectedMode changes
        this.gameMode = '不限模式';
        this.selectPass = '已有通行证';
        this.currentTokens = '';
        this.toTokens = '';
        this.currentLevel = '';
        this.toLevel = '';
        this.rankType = '';
        this.selectedCurrentTask = '';
        this.selectedToTask = '';
        this.currentScore = '';
        this.beforeLevel = '';
        this.needGames = '';
    },

    // Form Validation
    validateForm() {
         if (!this.selectedServer) {
            uni.showToast({ title: '请选择游戏区服', icon: 'none' });
            return false;
        }
         if (!this.selectedMode) {
             uni.showToast({ title: '请选择代练类型', icon: 'none' });
            return false;
        }

        switch (this.selectedMode) {
            case '代币':
                if (!this.gameMode) { uni.showToast({ title: '请选择游戏模式', icon: 'none' }); return false; }
                if (this.currentTokens === '' || this.toTokens === '') { uni.showToast({ title: '请输入代币数量', icon: 'none' }); return false; }
                if (parseInt(this.toTokens) <= parseInt(this.currentTokens)) { uni.showToast({ title: '目标代币需大于当前代币', icon: 'none' }); return false; }
                break;
            case '宝典':
                 if (!this.gameMode) { uni.showToast({ title: '请选择游戏模式', icon: 'none' }); return false; }
                 if (this.currentLevel === '' || this.toLevel === '') { uni.showToast({ title: '请输入宝典等级', icon: 'none' }); return false; }
                 if (parseInt(this.toLevel) <= parseInt(this.currentLevel)) { uni.showToast({ title: '目标等级需大于当前等级', icon: 'none' }); return false; }
                break;
            case '排位赛':
                 if (!this.rankType) { uni.showToast({ title: '请选择排位类型', icon: 'none' }); return false; }
                 if (!this.selectedCurrentTask || !this.selectedToTask) { uni.showToast({ title: '请选择当前和目标段位', icon: 'none' }); return false; }
                 if (!this.validateRankOrder()) return false; // Re-validate rank order
                 if (this.currentScore === '') { uni.showToast({ title: '请输入当前胜点', icon: 'none' }); return false; }
                break;
            case '定位赛':
                 if (!this.rankType) { uni.showToast({ title: '请选择排位类型', icon: 'none' }); return false; }
                 if (!this.beforeLevel) { uni.showToast({ title: '请选择上赛季段位', icon: 'none' }); return false; }
                 if (!this.needGames) { uni.showToast({ title: '请选择需打场次', icon: 'none' }); return false; }
                break;
        }
        return true;
    },

    // Submit Order
    submitOrder() {
       if (!this.validateForm()) {
        return;
      }

      // Construct the formData object to pass
      const orderData = {
        server: this.selectedServerText,
        mode: this.selectedMode,
        gameMode: (this.selectedMode === '代币' || this.selectedMode === '宝典') ? this.gameMode : null,
        selectPass: (this.selectedMode === '代币' || this.selectedMode === '宝典') ? this.selectPass : null,
        currentTokens: this.selectedMode === '代币' ? this.currentTokens : null,
        toTokens: this.selectedMode === '代币' ? this.toTokens : null,
        currentLevel: this.selectedMode === '宝典' ? this.currentLevel : null,
        toLevel: this.selectedMode === '宝典' ? this.toLevel : null,
        rankType: (this.selectedMode === '排位赛' || this.selectedMode === '定位赛') ? this.rankType : null,
        currentTask: this.selectedMode === '排位赛' ? this.selectedCurrentTask : null,
        toTask: this.selectedMode === '排位赛' ? this.selectedToTask : null,
        currentScore: this.selectedMode === '排位赛' ? this.currentScore : null,
        beforeLevel: this.selectedMode === '定位赛' ? this.beforeLevel : null,
        needGames: this.selectedMode === '定位赛' ? this.needGames : null,
         // Add calculated price and time if available
        suggestedPrice: this.suggestedPrice,
        estimatedTime: this.estimatedTime,
      };

      // Remove null fields for cleaner object
       Object.keys(orderData).forEach(key => {
          if (orderData[key] === null) {
            delete orderData[key];
          }
        });

      console.log("准备提交的订单数据:", orderData);

      uni.navigateTo({
        url: `/pages/SubmitOrder/DL/YXLMsubmitOrder/index?formData=${encodeURIComponent(JSON.stringify(orderData))}`
      });
    }
  }
}
</script>

<style>
/* Added container styles */
.container {
    padding-bottom: 180rpx; /* Match footer height */
}
/* 表单样式 */
.form {
    width: 100%;
    background-color: #fff;
    padding: 20rpx 40rpx;
    box-sizing: border-box;
}

.form-item {
    margin-bottom: 30rpx;
    position: relative;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-bottom: 1rpx solid #f0f0f0; /* Add separator */
    padding-bottom: 30rpx;
}
.form-item:last-child {
    border-bottom: none;
}
/* Special style for pass item */
.pass-item .label {
    width: 20% !important; /* Override default width */
    flex-shrink: 0;
}
.pass-item .pass-handle {
    width: 80% !important;
    display: flex;
    justify-content: flex-end;
}
/* Style uni-data-checkbox buttons */
.pass-handle .uni-data-checklist .checklist-group .checklist-box{
     margin-left: 10rpx !important;
     margin-right: 0 !important;
}
.pass-handle .uni-data-checklist .checklist-group .checklist-box.is--button {
    border: 1px solid #007aff !important;
    border-radius: 8rpx !important;
    padding: 5rpx 20rpx !important;
}
.pass-handle .uni-data-checklist .checklist-group .checklist-box.is--button.is-checked {
    background-color: #007aff !important;
}
.pass-handle .uni-data-checklist .checklist-group .checklist-box.is--button .checklist-content{
    color: #007aff !important;
    font-size: 26rpx !important;
}
.pass-handle .uni-data-checklist .checklist-group .checklist-box.is--button.is-checked .checklist-content{
     color: #fff !important;
}


.form-item .label {
    width: 30%;
    height: 100%;
    display: block;
    font-size: 28rpx;
    color: #333; /* Darker label */
}

.form-item .handle {
    width: 70%;
    cursor: pointer; /* Indicate clickable */
}

.picker,
.input {
    width: 100%;
    height: 80rpx;
    border-radius: 8rpx;
    padding: 0 20rpx;
    font-size: 28rpx;
    color: #666;
}

.selected-tag {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    padding: 0 10rpx; /* Adjust padding */
    height: 50rpx;
    border-radius: 8rpx;
    font-size: 28rpx;
    color: #666;
}

.selected-tag image {
    padding-left: 15rpx; /* Adjust spacing */
    width: 24rpx;
    height: 24rpx;
}

/* 弹窗样式 */
.popup-content {
    display: flex;
    flex-direction: column;
    background-color: #fff;
    border-top-left-radius: 20rpx;
    border-top-right-radius: 20rpx;
}

.popup-content .top {
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 18px; /* Adjust size */
    font-weight: bold;
    padding: 30rpx 20rpx 20rpx;
    border-bottom: 1rpx solid #eee;
}

.popup-content .body {
    max-height: 70vh; /* Limit max height */
    display: flex;
}

.popup-nav {
    width: 200rpx;
    border-right: 1px solid #eee;
    background-color: #f8f8f8;
    height: 70vh; /* Match body max height */
}

.nav-item {
    padding: 25rpx 20rpx; /* Adjust padding */
    font-size: 28rpx;
    color: #666;
    text-align: center;
    border-bottom: 1rpx solid #eee;
}
.nav-item:last-child {
    border-bottom: none;
}

.nav-item.active {
    color: #1ba035;
    font-weight: bold;
    background-color: #fff;
}

.popup-scroll {
    flex: 1;
    height: 70vh; /* Match body max height */
}

.popup-group-title {
    font-size: 28rpx;
    font-weight: bold;
    color: #333;
    padding: 15rpx 20rpx; /* Adjust padding */
    border-bottom: 1px solid #eee;
    background-color: #f8f8f8;
}

.popup-item {
    padding: 25rpx 40rpx; /* Adjust padding */
    font-size: 28rpx;
    color: #333;
    border-bottom: 1px solid #f5f5f5;
    text-align: center;
    cursor: pointer;
}
.popup-item:active {
    background-color: #f0f0f0;
}

.popup-item:last-child {
    border-bottom: none;
}

.popup-item-title {
    font-size: 16px;
    font-weight: bold; /* Bolder title */
    padding: 15rpx 0 10rpx; /* Adjust padding */
    text-align: center;
    /* border-bottom: 1rpx solid #eee; */ /* Removed border */
    margin-bottom: 10rpx;
}

.popup-item-body {
    display: flex;
    flex-wrap: wrap;
    padding: 10rpx 20rpx; /* Adjust padding */
    justify-content: flex-start; /* Align items to start */
}
/* Specific styles for rank selection */
.rank-body {
     justify-content: flex-start;
}
.rank-item {
    min-width: 120rpx; /* Wider items for ranks */
    padding: 15rpx 20rpx !important; /* Adjust padding */
    margin: 8rpx !important; /* Adjust margin */
}


.popup-item-body .popup-item-body-item {
    display: flex;
    align-items: center;
    justify-content: center;
    min-width: 100rpx; /* Minimum width */
    padding: 15rpx 25rpx; /* Adjust padding */
    border: 1px solid #ccc; /* Lighter border */
    border-radius: 8rpx;
    box-sizing: border-box;
    margin: 10rpx;
    font-size: 26rpx;
    cursor: pointer;
}
.popup-item-body .popup-item-body-item:active {
     background-color: #e0e0e0;
     border-color: #bbb;
}

.popup-empty {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
    font-size: 28rpx;
    color: #999;
}

/* Input Popups (Tokens, Levels, Score) */
.input-popup .input-row {
    display: flex;
    align-items: center;
    padding: 25rpx 40rpx;
    border-bottom: 1rpx solid #eee;
}
.input-popup .input-row span {
    width: 30%;
    font-size: 28rpx;
    color: #333;
}
.input-popup .input-row input {
    flex: 1;
    font-size: 28rpx;
    text-align: right;
    color: #333;
}
.input-popup .input-row input::placeholder {
    color: #ccc;
}
.input-popup .score-input input::placeholder {
     font-size: 26rpx; /* Smaller placeholder for score */
}

.popup-footer {
    width: 100%;
    text-align: center;
    font-size: 30rpx; /* Larger font */
    padding: 25rpx;
    color: #666; /* Standard cancel color */
    border-top: 1px solid #eee;
    box-sizing: border-box;
    cursor: pointer;
}
.popup-footer:active {
    background-color: #f0f0f0;
}

.popup-footer2 {
    display: flex;
    align-items: center;
    width: 100%;
    text-align: center;
    font-size: 16px;
    color: #999;
    border-top: 1px solid #eee;
    box-sizing: border-box;
}

.popup-footer2 .cancel,
.popup-footer2 .confirm {
    display: block;
    width: 50%;
    padding: 25rpx;
    text-align: center;
    font-size: 16px;
    box-sizing: border-box;
    cursor: pointer;
}

.popup-footer2 .cancel {
    color: #198dda;
}
.popup-footer2 .cancel:active {
    background-color: #f2f2f2;
}

.popup-footer2 .confirm {
    background-color: #198dda;
    color: #fff;
}
.popup-footer2 .confirm:active {
    background-color: #157ab3;
}


.orderMsg {
    width: 100%;
    display: flex;
    padding: 30rpx 40rpx; /* Adjust padding */
    box-sizing: border-box;
    background-color: #f8f8f8; /* Light background */
    border-top: 1rpx solid #eee;
    border-bottom: 1rpx solid #eee;
}

.orderMsg .pay,
.orderMsg .time {
    width: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
}

.orderMsg .pay image,
.orderMsg .time image {
    width: 40rpx; /* Smaller icon */
    height: 40rpx;
    margin-right: 15rpx; /* Space between icon and text */
}

.orderMsg .pay .text,
.orderMsg .time .text {
    font-size: 26rpx; /* Adjust size */
    font-weight: normal; /* Normal weight */
    color: #666;
}
.price-highlight,
.time-highlight {
    color: red;
    font-weight: bold;
    margin-left: 5rpx;
}

.footer-placeholder {
    height: 180rpx; /* Match footer height + tip */
}

.footer {
    width: 100%;
    position: fixed;
    bottom: 0;
    left: 0;
    background-color: #fff; /* White background */
    z-index: 10;
    border-top: 1rpx solid #e0e0e0;
}

.footer .tip {
    width: 100%;
    font-size: 24rpx; /* Smaller tip */
    color: #999; /* Grey tip */
    background-color: #f8f8f8;
    padding: 15rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    box-sizing: border-box;
}

.footer .button {
    width: 100%;
    height: 100rpx;
    color: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #007aff; /* Primary button color */
    font-size: 32rpx;
    font-weight: bold;
    cursor: pointer;
}
.footer .button:active {
     background-color: #0056b3; /* Darker shade on press */
}
</style>